<?php
/**
 * IndexController - The default controller class
 *
 * @author
 * @version
 */
require_once 'Zend/Controller/Action.php';
class ProductController extends App_Zend_Controller_Action_Shop
{
	public function detailAction()
    {
    	$inviteCode = $this->getRequest()->getParam('invite', '');
		if (!empty($inviteCode)) {
			$session = new Zend_Session_Namespace('member');
        	$session->inviteCode = $inviteCode;
        	$this->view->productDetailCanonical = 1;	
		}
    	
    	define('OLDBADGE', 0);
    	$this->view->styleName = "product";
        $id = $this->_request->getParam('id');
        $itemid = $id;
        $item = new CItem();
        $itemArray = $item->getDetail($itemid,'product');
        $product_pattern_stock = unserialize($itemArray[0]['product_pattern_stock']);
        $stocknum =0;
        foreach($product_pattern_stock as $v){
        	$stocknum+=$v;
        }
        $this->view->assign('stocknum',$stocknum);
        if($itemArray[0]['flid']==342){
        	throw new Exception('Error');
        }
        $item->updateViewNum($itemid, 'product');
        
        
        $itemDetailArray=$item->getDetail($itemid,'product');
        //简介缩短
        //$itemDetailArray[0]['description'] = mb_substr( $itemDetailArray[0]['description'],0,96,'UTF-8');
        
        //获取配件
        $accessory = new CProductaccessory();
        $adata = $accessory->getProductAccessory($itemid);        
        $itemidArray=array();
        foreach($adata as $k=>$v){
        	$itemidArray[]=$v['itemid'];
        }
        $flidaccessoryid = $accessory->getFenleiAccessory($itemArray[0]['flid']);

    	if(!empty($flidaccessoryid)){
        	foreach($flidaccessoryid as $value){
        		if(!in_array($value['accessoryid'], $itemidArray)){
        			$adata[]=$accessory->getAccessoryInfo($value['accessoryid'],$value['itemid'],$value['flid']);
        		}
        	}
        }
        foreach($adata as $k=>$v){
        	$adata[$k]['accessory_size'] = unserialize($v['product_pattern']);
			if ($v['sku']) {
        		$skuArr = CStock::getStock($v['sku']);
        		if ($skuArr) {
        			$adata[$k]['accessory_size'] = $skuArr['size'];
        		}
        	}
        }
        $productObj = new CProduct();
        $info = $productObj->getDetail($itemid);
        $size = unserialize($info[0]['product_pattern']);
        $this->view->assign('accessory_size',$size);
        $this->view->assign('adata',$adata);
        
        $mlm = new CMlm();
        //用户存在该坑位
        $uid = isset($_COOKIE[COOKIE_PRE . 'uid']) ? $_COOKIE[COOKIE_PRE . 'uid'] : 0;
        if ($uid) {
        	$flashCommon = new CFlashcommon();
        	if ($flashCommon->isUserFlashItem($uid, $itemid) || $flashCommon->isUserWhenEverFlashItem($uid, $itemid)) {
        		$flashSaleCommon = new CFlashsales();        		
        		$productAttr = new CProductattr();
        		if ($productAttr->getAttr($itemid, 11)) {
        			$itemDetailArray[0]['min_price'] = 23.99;
        		} elseif ($productAttr->getAttr($itemid, 12)) {
        			$itemDetailArray[0]['min_price'] = 28.99;
        		} else {
        			$discount = $flashSaleCommon->getDiscount($itemid);
        			$itemDetailArray[0]['max_price'] = round($itemDetailArray[0]['max_price'] * $discount,2);
        			$itemDetailArray[0]['min_price'] = $itemDetailArray[0]['max_price'];
        		}
        	}
        	
        	//传销
			$inviteCode = $mlm->memberInviteCode($_COOKIE[COOKIE_PRE . 'uid']);
			$this->view->inviteCode = $inviteCode;	
			$flashCommon = new CFlashcommon();        
        	$creditAmount = $flashCommon->getAvaiAmount($_COOKIE[COOKIE_PRE . 'uid']);
        	$this->view->creditAmount = $creditAmount;
        }
        $rebateArray = $mlm->getConfig();
	    $this->view->rebatePersent = $rebateArray['rebate']['rebate_percent_1'];
        //

		$itemDetailArray[0]['content']=str_replace('gogoalshop','fancycheapjersey',$itemDetailArray[0]['content']);

        
        $this->view->assign('itemDetailArray',$itemDetailArray);
        $this->view->assign('isOurOwnProduct',1);
        
        $tmpfuid = $item->getitemfuid($itemDetailArray[0]['flid']);
        $CFenlei=new CFenlei("product");
        $select_badgepatch = null;
        if(!empty($itemDetailArray[0]['select_badgepatch_p'])) {
            $select_badgepatch = unserialize($itemDetailArray[0]['select_badgepatch_p']);
        }
        if (!OLDBADGE) {  
        	$badge = new CBadge();
        	$select_badgepatch = $badge->getItemBadge($itemid);
        }        
        $this->view->assign('select_badgepatch',is_array($select_badgepatch)?$select_badgepatch:array());
        
        if ($tmpfuid) {
	        $fuitemDetailArray=$CFenlei->getoneFenlei($tmpfuid);
	        $this->view->assign('fuitemDetailArray',$fuitemDetailArray);
        }
        
        $lengthstature = unserialize($fuitemDetailArray[0]['lengthstature']);
        $this->view->assign('lengthstature',is_array($lengthstature)?$lengthstature:array());
        
		$isNewItemArray=$item->getAllItems(0,8,'product',0,0,"has_banned","type='2'",'view_num DESC');
        $this->view->assign('isNewItemArray',$isNewItemArray);
		
        $this->getHelper('Fenlei')->getCategories();
		
        $price=new CProductPrice();
		$priceArray=$price->getAllPrice($itemid);
		$attachment=new CAttachment();
		$attachmentArray=$attachment->getAttachments($itemid ,'cut_url !=""');
		$this->view->assign('attachmentArray',$attachmentArray);
		$this->view->assign('priceArray',$priceArray);
		$this->view->assign('itemid',$itemid);
		
		$parentArray=$this->getHelper('Fenlei')->getAllParents($this->view,$itemDetailArray[0]['flid']);
		$parentArray[]=$itemDetailArray[0]['subject'];
		$navFlString=join(' &gt;&gt; ',$parentArray);
		$this->view->assign ( "navFlString", $navFlString );
		$this->view->parentArray = $parentArray;
		
		//$pattern_size=unserialize($itemDetailArray[0]['product_pattern']);
		//$this->view->assign('pattern_size',is_array($pattern_size)?$pattern_size:array());
		$pattern_size=unserialize($itemDetailArray[0]['product_pattern']);
            $pattern_size_stock=unserialize($itemDetailArray[0]['product_pattern_stock']);
            if (is_array($pattern_size_stock)) {
            	$new_pattern_size_stock = array();
	            for($i = 0; $i < count($pattern_size); $i++) {
					if (isset($pattern_size_stock[$pattern_size[$i]]) && $pattern_size_stock[$pattern_size[$i]] > 0) {
						$new_pattern_size_stock[] = $pattern_size[$i];
					}
	            }
            } else {
            	$new_pattern_size_stock = $pattern_size;
            }
		$this->view->assign('pattern_size',is_array($new_pattern_size_stock)?$new_pattern_size_stock:array());
		//存在sku
		if ($itemDetailArray[0]['sku']) {
			$skuArr = CStock::getStock($itemDetailArray[0]['sku']);
			if ($skuArr) {
				$this->view->assign('pattern_size', $skuArr['size']);
				if ($skuArr['is_forlong']) {
					$this->view->assign('stocknum', 1000);
				} else {
					$this->view->assign('stocknum', $skuArr['stocknum']);
				}
			}
		}
		//sku远程库存结束
		$select_Original=unserialize($itemDetailArray[0]['select_Original']);
		$this->view->assign('select_Original',is_array($select_Original)?$select_Original:array());
		$this->view->assign ( "website_title", $itemDetailArray[0]['subject'].' -- '.$this->view->toText($navFlString) );
		$this->view->assign ( "website_description", $this->view->subStr($this->view->toText($itemDetailArray[0]['pattern_intro']),0,150) );
		$interrelatedArray=array();
            if($itemArray[0]['interrelated'])
            {
                $where=R_PRE.'items.itemid in ('.$itemArray[0]['interrelated'].') and is_showed=1';

                $itemShow=new CItemShow();

                $itemShow->setType('product');

                $itemShow->setWhere($where);

                $itemCounts=$itemShow->getAllItemCounts();

                Zend_Loader::loadClass("CFilter");

                $pageArray = CFilter::filterPage ( $page, $itemCounts, 12 );

                $itemShow->setFromTo(array('counts'=>12,'from'=>$pageArray['from']));

                $myorder='';

                if($order=='0')
                {

                    $myorder=R_PRE."items.add_time DESC";

                }elseif($order=='1')
                {

                    $myorder=R_PRE."products.min_price DESC";

                }elseif($order=='2')
                {

                    $myorder=R_PRE."products.min_price ASC";

                }else{
					$myorder = 'field('.R_PRE.'items.itemid,'.$itemArray[0]['interrelated'].')';
				}

                $itemShow->setOrder($myorder);
                $interrelatedArray=$itemShow->getAllItems();
                Zend_Loader::loadClass("CPage");
                $pageString = CPage::divPages( $pageArray ['pageNumber'], $pageArray ['page'], MY_URL."/category-detail-cid-$id/?order=$order");
            }
            $this->view->assign('interrelatedArray',$interrelatedArray);
		
        $review = new CProductreview();
        $this->view->reviewCount = $review->getReviewCount($itemid, $itemDetailArray[0]['subject'], $itemDetailArray[0]['view_num'], $this->view->reviewCount);
        
        //$review->addReviewRand($itemid, $itemDetailArray[0]['subject'], $itemDetailArray[0]['view_num'], $this->view->reviewCount);        
		//$this->view->reviewCount = $review->getPageCount($itemid);
		
        $avg = $review->average($itemid);
        
        $allCount = $review->allcount(0, $itemid, 1);
 		if ($allCount[0]['count'] > 0) { 			
 			$count5 = $review->allcount(5, $itemid);
 			$this->view->count5 = round(($count5[0]['count']/$allCount[0]['count'])*100);
 			$count4 = $review->allcount(4, $itemid);
 			$this->view->count4 = round(($count4[0]['count']/$allCount[0]['count'])*100);
 			$count3 = $review->allcount(3, $itemid);
 			$this->view->count3 = round(($count3[0]['count']/$allCount[0]['count'])*100);
 			$count2 = $review->allcount(2, $itemid);
 			$this->view->count2 = round(($count2[0]['count']/$allCount[0]['count'])*100);
 			$count1 = $review->allcount(1, $itemid);
 			$this->view->count1 = round(($count1[0]['count']/$allCount[0]['count'])*100);
 		}  else {
 			$this->view->count5 = 0;
 			$this->view->count4 = 0;
 			$this->view->count3 = 0;
 			$this->view->count2 = 0;
 			$this->view->count1 = 0;
 		}
 		
 		$keyModel = new CKeywords();
 		$this->view->relateKey = $keyModel->getRelateKey($itemDetailArray[0]['productid']);
        $this->view->keyModel = $keyModel;
        $this->view->popSearch = $keyModel->getDetailPopKey($itemDetailArray[0]['productid']);
 		
        $this->view->avgAll = round(($avg[0]['product_avg']+$avg[0]['ship_avg']+$avg[0]['overall_avg'])/3);
        $this->view->avgProduct = round($avg[0]['product_avg']);
        $this->view->avgShip = round($avg[0]['ship_svg']);
        $this->view->avgOver = round($avg[0]['overall_avg']);       
        $this->view->product = 1;
        $this->view->webSiteTitle = $itemDetailArray[0]['subject'] . ', ' . $this->view->toText($parentArray[count($parentArray)-2]) . ', Cheap Soccer Jerseys';
        $this->view->webSiteDescription = empty($itemDetailArray[0]['description']) ? str_replace("\"","",$itemDetailArray[0]['subject']) . ' sale' : str_replace("\"","",$itemDetailArray[0]['description']);
        $this->view->webSiteKeywords = empty($itemDetailArray[0]['keywords']) ? $itemDetailArray[0]['subject'] . ' sale' : $itemDetailArray[0]['keywords'];
		
		$this->view->webSiteFacebookUrl = MY_URL . '/pd-' . $itemDetailArray[0]['itemid'].'.html';
		
		/*属性筛选*/
		$attr = new CAttr();
        $categoryAttr = $attr->getByType(1);	
        $brandAttr = $attr->getByType(2);	
        $playerAttr = $attr->getByType(3);
        
        $this->view->categoryAttr=$categoryAttr;
        $this->view->brandAttr=$brandAttr;
        $this->view->playerAttr = $playerAttr;
        
        $this->view->isshowchoose = 1;
        
        $flashSale = new CFlashsales();
        $this->view->isFlashSale = $flashSale->isFlashItem($itemid);
        $flashCommon = new CFlashcommon();
        $this->view->isSuit = $flashCommon->isSuit($itemid);
    }
    
    
    public function getreviewAction()
    {
    	$this->getHelper('layout')->disableLayout();
    	$page = intval($this->getRequest()->getParam('page'));
    	$pageNum = 10;
    	if ($page == 0) {
    		$page = 1;
    	}
    	$itemid = intval($this->getRequest()->getParam('id'));
    	$review = new CProductreview();
        $counts = $review->getPageCount($itemid, 1);
        $pageCount = ceil($counts/$pageNum);
        
        $reviewList = $review->fetchReview($page,$pageNum,$itemid);
        $this->view->reviewList = $reviewList;
        $this->view->buyer = new CBuyer();
        $this->view->pageCount = $pageCount;
        $this->view->page = $page;
        $this->view->id = $itemid;
    }

    public function addtocartAction()
    {
    	
        $this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
        $pattern_name=$this->_request->getParam('pattern_name');
        $pattern_size=$this->_request->getParam('pattern_size');
        $select_Original=$this->_request->getParam('select_Original');
        $countsArray=$this->_request->getParam('counts');
        $addNameNum=$this->_request->getParam('addNameNum');
        $BadgePatch=$this->_request->getParam('BadgePatch');
        $printMesg = $this->_request->getParam('printMesg');
        $print_meno = '';
        $accessory_id = $this->_request->getParam('accessoryid');
        $accessory_price = $this->_request->getParam('price');
        $accessory_name = $this->_request->getParam('subject');
        $accessory_size = $this->_request->getParam('accessorysize');
        $flag = $this->_request->getParam('flag');
        $quantity = $this->_request->getParam('quantity');
        $accessory ='';
        if($addNameNum == 1) {	
        	$allparams = $this->_request->getParams();
        	foreach ($allparams as $k=>$v) {
        		$allparams_key .= $k . '|';
        	}
        	preg_match_all( "/printorginal_(\d+)/" , $allparams_key , $matches);       	
        	
        	$seting_array = array();
        	foreach ($matches[1] as $v) {
        		$seting_array[] = $this->_request->getParam('printorginal_'.$v);
        	}       	
        	
        	unset($allparams,$allparams_key,$matches);
        	
        	$printshirtAmount = $this->_request->getParam('printshirtAmount');
	        $printAmounts = 0;
	        foreach ($printshirtAmount as $k=>$v) {
	        	if((int)$v == 0)
	        		continue;
	        	$printAmounts = (int)$v + $printAmounts;
	        }
        	$select_badgepatch=$this->_request->getParam('select_badgepatch');
        	$printshirtAmount = $this->_request->getParam('printshirtAmount');
        	$printshirtSize = $this->_request->getParam('printshirtSize');
        	$printshirtNum = $this->_request->getParam('printshirtNum');
        	$printshirtName = $this->_request->getParam('printshirtName');
        	$printshirtNumCus = $this->_request->getParam('printshirtNumCus');
        	$printshirtNameCus = $this->_request->getParam('printshirtNameCus');
        	$printshirtName = $this->_request->getParam('printshirtName');
        	$Originalnum = $this->_request->getParam('Originalnum'); 
        	$myPrintAmount = 0;
        	$myOrigialAmount = 0;  
        	$myPatchAmount = 0;
        	
        	$badgepatchFlag = 0;
        	$print_meno = '';
        	$badgeMoney = 0;
        	
        	foreach ($printshirtAmount as $k=>$v) {        		
        		if((int)$v == 0)
        			continue;
        		$print_meno .= "Size:{$printshirtSize[$k]},Amount:{$printshirtAmount[$k]}";
        		if($seting_array[$k] == 1)
        		{
        			if ($Originalnum[$k] != '0') {
        				if (!empty($printshirtNameCus[$k]) || !empty($printshirtNumCus[$k])) {
        					$print_meno .= ",SelectOrginalNum:{$Originalnum[$k]}, Want Print: [Name:$printshirtNameCus[$k], Num:$printshirtNumCus[$k]]";
        				} else {
        					$print_meno .= "";
        				}
        			} else {        				
        				$print_meno .= ",SelectOrginalNum:None, Want Print: [Name:$printshirtNameCus[$k], Num:$printshirtNumCus[$k]]";
        			}
        			if (!empty($printshirtNameCus[$k]) || !empty($printshirtNumCus[$k])) {
        				$myOrigialAmount += $printshirtAmount[$k];
        			}
        		} elseif (isset($printshirtName[$k])) {
        			if (!empty($printshirtName[$k]) || !empty($printshirtNum[$k])) {
        				$print_meno .= ",Customize:[Name:{$printshirtName[$k]},Num:{$printshirtNum[$k]}]";
        			} else {
        				$print_meno .= "";
        			}
        			if (!empty($printshirtName[$k]) || !empty($printshirtNum[$k])) {
        				$myPrintAmount += $printshirtAmount[$k];
        			}
        		}        		
        		if (isset($select_badgepatch[$k]) && !empty($select_badgepatch[$k])) {        			
        			$badgepatchFlag = 1;
        			$myPatchAmount += $printshirtAmount[$k];
        			preg_match('/.*\$(\d+)/', $select_badgepatch[$k], $match);
        			if (isset($match[1])) {
        				$badgeMoney = $badgeMoney + $match[1] * $printshirtAmount[$k];
        			}
        			$print_meno .= ",<br/>BadgePatch:$select_badgepatch[$k] | ";
        		} else {        			
        			$print_meno .= ",<br/>BadgePatch: no | ";
        		}
        		
        		
        	}        	
        }
        
        
        $counts=0;
        $patternContent='';
        $product = new CProduct();
        $itemid = $this->_request->getParam('itemid');
                
        /**
         * 购物车行为跟踪
         */
        $productLog = new CProductlog();
        $productLog->insert(array('uid'=>isset($_COOKIE[COOKIE_PRE.'uid']) ? $_COOKIE[COOKIE_PRE.'uid'] : 0, 'itemid'=>$itemid, 'ip'=>$_SERVER['REMOTE_ADDR'], 'addtime'=>date('Y-m-d H:i:s', time())));
       /**
        * end
        */
        
        for($i=0;$i<count($countsArray);$i++) {
            if($countsArray[$i]!=0) {
                $counts+=$countsArray[$i];
                $patternContent.=$pattern_size[$i].':'.$countsArray[$i];
                //不必更新，只要知道库存多少
                $stock = $product->getPatternStock($pattern_size[$i], $countsArray[$i], $itemid);
                if ($stock > 0) {
                	$patternContent .= ', ';
                } else {
                	$patternContent .= ',[This size sold out, please wait for 5-7 days], ';
                }
            }
        }   
        
        $cookieArray=array(
        	$itemid=>array(
        		'pattern_name'=>$pattern_name,
        		'counts'=>$counts,
        		'pattern_size'=>$patternContent,
        		'printMesg'=>$print_meno . $printMesg,        		
        		'badge_patch_amount'=>$myPatchAmount,
        		'badge_patch_money'=>$badgeMoney,
        	)
        );
        $cookieArray[$itemid]['accessory']="";
        if(is_array($flag)){
        	foreach($flag as $k=>$v){
        		if($v==1){
        			$cookieArray[$itemid]['accessory'].="Name:<a href='/pd-". $accessory_id[$k].".html'>".$accessory_name[$k]."</a>,Price:$".$accessory_price[$k].",Size:".$accessory_size[$k].",Quantity:".$quantity[$k]."|";
        			
        			$cookieArray[$itemid]['accessory_id'][$k] = $accessory_id[$k];
        			$cookieArray[$itemid]['accessory_price'][$k] = $accessory_price[$k];
        			$cookieArray[$itemid]['accessory_name'][$k] = $accessory_name[$k];
        			$cookieArray[$itemid]['accessory_size'][$k] = $accessory_size[$k];
        			$cookieArray[$itemid]['quantity'][$k] = $quantity[$k];
        		}
        		
        	}
        	$cookieArray[$itemid]['accessory']=trim($cookieArray[$itemid]['accessory'],"|");
        }
        if ($badgepatchFlag) {
        	$cookieArray[$itemid]['BadgePatch'] = 'Yes';
        } else {
        	$cookieArray[$itemid]['BadgePatch'] = 'No';
        }
        
        if ($myOrigialAmount > 0) {
        	$cookieArray[$itemid]['originalname_num'] = $myOrigialAmount;
        	$cookieArray[$itemid]['originalprintAmounts'] = $myOrigialAmount;
        } else {
        	$cookieArray[$itemid]['originalname_num'] = '';
        	$cookieArray[$itemid]['originalprintAmounts'] = '';
        }
    	if ($myPrintAmount > 0) {
        	$cookieArray[$itemid]['name_num'] = $myPrintAmount;
        	$cookieArray[$itemid]['printAmounts'] = $myPrintAmount;
        } else {
        	$cookieArray[$itemid]['name_num'] = '';
        	$cookieArray[$itemid]['printAmounts'] = '';
        } 
        /**又收钱了
        $flashSale = new CFlashsales();
        if ($flashSale->isFlashItem($itemid)) {
        	$cookieArray[$itemid]['originalprintAmounts'] = 0;
        	$cookieArray[$itemid]['printAmounts'] = 0;
        	$cookieArray[$itemid]['badge_patch_money']= 0;
        }**/
        $sessionHash = $_COOKIE[COOKIE_PRE.'product_buy_session'];
		$cart = new CCart();
        $shoppingArray=array();
        $member = new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
        	//未登录
	        if($sessionHash != '') {
				$cartStr = $cart->getCartStr($sessionHash);
				if ($cartStr) {
	           		$shoppingArray=json_decode(stripslashes($cartStr),true);
				} else {
					$sessionHash = $cart->sessionHash();
				}			
	        } else {
	        	$sessionHash = $cart->sessionHash();
	        }
        } else {
        	//登录
        	$sessionHash = $cart->sessionHash();
        	$cartStr = $cart->getCartStrByUid($_COOKIE[COOKIE_PRE.'uid']);
        	if ($cartStr) {
	           	$shoppingArray=json_decode(stripslashes($cartStr),true);
			}
        }
        
        if(isset($cookieArray[$itemid])) {
            $shoppingArray[$itemid]=$cookieArray[$itemid];
        }
       
        $cartStr = json_encode($shoppingArray);
        
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
        	//未登录
        	$row = array('cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180);
        	setcookie(COOKIE_PRE.'product_buy_session', $sessionHash, time()+3600*24*180,'/');
			$cart->setCartStr($sessionHash, $row);
        } else {
        	//登录
        	$row = array('cart_session_id'=>$sessionHash, 'cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180, 'uid'=>$_COOKIE[COOKIE_PRE.'uid']);
        	$cart->setCartStrByUid($_COOKIE[COOKIE_PRE.'uid'], $row);
        }      
		
        $this->_redirect(MY_URL.'/product-showitem');
    }
    
    public function clearcartAction()
    {
    	$this->getHelper('viewRenderer')->setNorender();
    	$this->getHelper('layout')->disableLayout();
    	$cart = new CCart();
    	$db = $cart->getAdapter();
    	$member = new CMember();
    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
    		$where = $db->quoteInto('cart_session_id = ?', $_COOKIE[COOKIE_PRE . 'product_buy_session']);    
    	} else {
    		$where = $db->quoteInto('uid = ?', $_COOKIE[COOKIE_PRE . 'uid']);
    	}	
    	if ($cart->delete($where)) {
    		echo 1;
    	} else {
    		echo 0;
    	}    	
    }

    public function showitemAction()
    {
    	//判断下架产品
    	$sessionHash = $_COOKIE[COOKIE_PRE.'product_buy_session'];
		$cart = new CCart();
        $shoppingArray=array();
        $member = new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
        	//未登录
	        if($sessionHash != '') {
				$cartStr = $cart->getCartStr($sessionHash);
				if ($cartStr) {
	           		$shoppingArray=json_decode(stripslashes($cartStr),true);
				} else {
					$sessionHash = $cart->sessionHash();
				}		
	        } else {
	        	$sessionHash = $cart->sessionHash();
	        }
        } else {
        	//登录
        	$sessionHash = $cart->sessionHash();
        	$cartStr = $cart->getCartStrByUid($_COOKIE[COOKIE_PRE.'uid']);
        	if ($cartStr) {
	           	$shoppingArray=json_decode(stripslashes($cartStr),true);
			}
        }
        $productModel = new CProduct();
        foreach ($shoppingArray as $k=>$v) {
        	$product = $productModel->getDetail($k);
        	
        	if (!empty($product)) {
        		if ($product[0]['is_showed'] == 0) {
        			unset($shoppingArray[$k]);
        		}
        	} else {
        		unset($shoppingArray[$k]);
        	}
        }
        $cartStr = json_encode($shoppingArray);
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
        	//未登录
        	$row = array('cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180);
        	setcookie(COOKIE_PRE.'product_buy_session', $sessionHash, time()+3600*24*180,'/');
			$cart->setCartStr($sessionHash, $row);
        } else {
        	//登录
        	$row = array('cart_session_id'=>$sessionHash, 'cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180, 'uid'=>$_COOKIE[COOKIE_PRE.'uid']);
        	$cart->setCartStrByUid($_COOKIE[COOKIE_PRE.'uid'], $row);
        }
        
    	//
    	$this->view->styleName = 'cart';
    	$this->view->webSiteTitle = 'My shopping cart';
    	$this->view->webKeywords = 'My shopping cart';
    	//$this->view->webDescript = 'My shopping cart';
     	$this->getHelper('Item')->getOrderItemArray();
     	$member = new CMember();
     	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
     		$this->view->hasLog = 0;
     	} else {
     		$this->view->hasLog = 1;
     		$user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
	        $score = new CScore();
	        $userDollar = $score->score2dollar($user[0]['integral']);
	        $this->view->userDollar = $userDollar;
	        /**
	         * 活动添加的代码
	         */
	        //var_dump($this->view->itemArray);
	        $totalAmount = 0;
	        $i = 0;
	        $fitstTwoPrice = 0;
	        
	        if(is_array($this->view->itemArray)){
		        foreach ($this->view->itemArray as $k=>$v) {
		        	$totalAmount += $v['amounts'];
		        	if ($i < 2) {
		        		$firstTwoPrice += $v['net_price'] ;
		        	}
		        	$i++;
		        }	 
	        }
			if (count($this->view->itemArray) == 1) {
				$firstTwoPrice = $this->view->itemArray[0]['net_price']*2 ;
			}
			
	        $game = new CGame();
	        if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {	        	
		        if ($totalAmount <= 2) {
		        	$this->view->userDollar = $this->view->totalPriceOrg;		        	
		        } else {
		        	$this->view->userDollar = $firstTwoPrice;
		        }
		        $this->view->validatePrize = 1;
	        } else {
	        	$this->view->validatePrize = 0;
	        }	        	        
	        /**end*/
     	}
     	
     	/*cart also like*/
     	$db = Zend_Registry::get('db');
    	$interrelatedArray = array();
    	$flarray = array();
    	if( count($this->view->itemArray) > 0 ) {
	    	foreach ($this->view->itemArray as $ci) {
	    		try{
	    			$flid = $db->fetchOne("SELECT `flid` FROM `zcshop_items` where `itemid`={$ci['itemid']}");
	    		}catch (Exception $e) {
	    			continue;
	    		}
	    		if($flid == '')
	    			continue;
	    		$flarray[] = $flid;
	    	}
    	}
//    	var_dump($flarray);
    	
    	if( count($flarray) == 1 ) {
    		$limit = 5;
    	} else {
    		$limit = 5 * 2;
    	}
    	if( count($flarray) > 0 ) {
    		$flstring = join(',',$flarray);
//    		echo $flstring . '<hr />';
    		$sql = "SELECT ti.`itemid`,ti.`flid`,ti.`subject`,ti.`view_num`,ti.`item_type`,tp.`cut_url`,tp.`min_price`,tp.`max_price`,tp.`m_org_price`,tp.`is_showed` FROM `zcshop_items` ti left join `zcshop_products` tp on ti.`itemid`=tp.`itemid` WHERE ti.`flid` in ($flstring) and ti.`item_type`='product' and tp.`is_showed`=1 order by ti.`view_num` desc limit $limit";
    		$interrelatedArray = $db->fetchAll($sql);
//    		echo $sql . '<hr />';
//    		var_dump($interrelatedArray);
    	}
    	if( count($flarray) == 0 ) {
    		$sql = "SELECT ti.`itemid`,ti.`flid`,ti.`subject`,ti.`view_num`,ti.`item_type`,tp.`cut_url`,tp.`min_price`,tp.`max_price`,tp.`m_org_price`,tp.`is_showed` FROM `zcshop_items` ti left join `zcshop_products` tp on ti.`itemid`=tp.`itemid` WHERE ti.`item_type`='product' and tp.`is_showed`=1 order by ti.`view_num` desc limit 5";
    		$interrelatedArray = $db->fetchAll($sql);
//    		echo $sql . '<hr />';
//    		var_dump($interrelatedArray);
    	}
//    	var_dump($interrelatedArray);
//    	exit;
		$this->view->interrelatedArray = $interrelatedArray;
		
		$this->view->noLongBanner = 1;
     	
    }

    public function updateAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $method=$this->_request->getParam('method');
        if ($method == 'contact') {
            $this->_redirect(MY_URL.'/product-addcontact');
        } elseif ($method == 'self'){
            $this->_redirect(MY_URL.'/product-showitem');
        }
    }

    public function removeAction()
    {
    	$product = new CProduct();
        $this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
        $itemid=$this->_request->getParam('itemid');
        $pattern_name=urldecode($this->_request->getParam('pattern_name'));
        if($itemid == '') {
            die($itemid);
            setcookie(COOKIE_PRE.'product_buy_session',null,-1,'/');
        } else {
        	$cart = new CCart();
        	$member = new CMember();
        	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	        	//未登录
	        	$sessionHash=$_COOKIE[COOKIE_PRE.'product_buy_session'];
				$cartStr = $cart->getCartStr($sessionHash);
				if (!$cartStr) {
					return ;
				}
        	} else {
        		$sessionHash=$_COOKIE[COOKIE_PRE.'product_buy_session'];
        		$cartStr = $cart->getCartStrByUid($_COOKIE[COOKIE_PRE.'uid']);
        	}
            if (empty($sessionHash)) {
            	$sessionHash = $cart->sessionHash();
            }
            $shoppingArray=json_decode(stripslashes($cartStr),true);
            $newShoppingArray=array();
            foreach ((array)$shoppingArray as $key => $value)
            {
                if($pattern_name!=$value['pattern_name']&&$key==$itemid)
                {
                    $newShoppingArray[$key]['pattern_name']=$value['pattern_name'];

                    $newShoppingArray[$key]['counts']=$value['counts'];

                    $newShoppingArray[$key]['pattern_size']=$value['pattern_size'];
                     
                    $newShoppingArray[$key]['printMesg']=$value['printMesg'];
                      
                    $newShoppingArray[$key]['printAmounts']=$value['printAmounts'];
                    $newShoppingArray[$key]['badge_patch_amount']=$value['badge_patch_amount'];
                    $newShoppingArray[$key]['badge_patch_money']=$value['badge_patch_money'];
                    $newShoppingArray[$key]['BadgePatch']=$value['BadgePatch'];
                    $newShoppingArray[$key]['originalname_num']=$value['originalname_num'];
                    $newShoppingArray[$key]['originalprintAmounts']=$value['originalprintAmounts'];
                    $newShoppingArray[$key]['name_num']=$value['name_num'];
                    $newShoppingArray[$key]['printAmounts']=$value['printAmounts'];
                    $newShoppingArray[$key]['printMesg'] = $value['printMesg'];
                    $newShoppingArray[$key]['accessory_name'] = $value['accessory_name'];
                    $newShoppingArray[$key]['accessory_price'] = $value['accessory_price'];
                    $newShoppingArray[$key]['accessory_size'] = $value['accessory_size'];
                    $newShoppingArray[$key]['quantity'] = $value['quantity'];
                    $newShoppingArray[$key]['accessory'] = $value['accessory'];
                    
                    
                }elseif($key!=$itemid)
                {

                    $newShoppingArray[$key]['pattern_name']=$value['pattern_name'];

                    $newShoppingArray[$key]['counts']=$value['counts'];

                    $newShoppingArray[$key]['pattern_size']=$value['pattern_size'];

                    $newShoppingArray[$key]['printMesg']=$value['printMesg'];
					
                	$newShoppingArray[$key]['accessory_name'] = $value['accessory_name'];
                    $newShoppingArray[$key]['accessory_price'] = $value['accessory_price'];
                    $newShoppingArray[$key]['accessory_size'] = $value['accessory_size'];
                    $newShoppingArray[$key]['quantity'] = $value['quantity'];
                    $newShoppingArray[$key]['accessory'] = $value['accessory'];
                    
                    $newShoppingArray[$key]['printAmounts']=$value['printAmounts'];
                    
                    $newShoppingArray[$key]['badge_patch_amount']=$value['badge_patch_amount'];
                    $newShoppingArray[$key]['badge_patch_money']=$value['badge_patch_money'];
                    $newShoppingArray[$key]['BadgePatch']=$value['BadgePatch'];
                    $newShoppingArray[$key]['originalname_num']=$value['originalname_num'];
                    $newShoppingArray[$key]['originalprintAmounts']=$value['originalprintAmounts'];
                    $newShoppingArray[$key]['name_num']=$value['name_num'];
                    $newShoppingArray[$key]['printAmounts']=$value['printAmounts'];

                } elseif($pattern_name==$value['pattern_name']&&$key==$itemid){
                	//不用管了。
                	//$product->updateStock("+{$value['counts']}", $itemid);
//                	$sizeArr = explode(',', $value['pattern_size']);
//					foreach ($sizeArr as $v) {
//						preg_match('/(.*):(\d+)/', $v, $match);										
//						if ($match) {	
//							$product->updatePatternStock($match[1], $match[2], $itemid, 'add');
//						}
//					}                	
                }              		
            }
            $cartStr=json_encode($newShoppingArray);
            if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	        	//未登录
	        	$row = array('cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180);        	
				$cart->setCartStr($sessionHash, $row);
	        } else {
	        	//登录
	        	$row = array('cart_session_id'=>$sessionHash, 'cart_str'=>addslashes($cartStr), 'expires'=>time()+3600*24*180, 'uid'=>$_COOKIE[COOKIE_PRE.'uid']);
	        	$cart->setCartStrByUid($_COOKIE[COOKIE_PRE.'uid'], $row);
	        }   			
        }
        
        $this->_redirect(MY_URL.'/product-showitem');
    }
    public function getsizeAction(){
    	$itemid = $this->_getParam('itemid');
    	$productObj = new CProduct();
    	$info = $productObj->getDetail($itemid);
    	$size = unserialize($info[0]['product_pattern']);
    	echo json_encode($size);
    	exit();
    }   
        
    public function payorderAction()
    {
    	$this->getHelper('layout')->disableLayout();
    	$this->view->styleName = 'order';
    	$this->view->webSiteTitle = 'Pay My Order';
    	$this->view->webSiteKeywords = 'Pay My Order';
    	$this->view->webSiteDescription = 'Pay My Order';
    	
    	$member = new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            //$this->_redirect(MY_URL.'/auth-login?preurl=product-payorder');
            //$this->getHelper('viewRenderer')->setNoRender();
            // echo '0'; //Please Login In
            //return;
            //注册空白帐户
            $this->view->hasLog = 0;
            if (!isset($_SESSION['uid'])) {
	        	if ($this->getRequest()->isPost()) {
		            $commonData=array(
			                'username'=>'',
			                'userpass'=>'',
			        		'passwd'=>'',
			                'email'=>$this->getRequest()->getParam('email'),
			        		'clubid'=>'',
		        			'subscribe'=>1,
			                'reg_time'=>time(),
			        		'reg_from' =>'none',
			                'reg_ip'=>$this->getHelper('User')->getIp(),
			                'member_type'=>'buyer',
			                'email_code'=>'1',
			                'is_enterprice'=>'0',	        		
			        );
			        $buyerData=array(
	                	'nick_name'=>'fancycheapjersey_' . date('Ymd') . rand(0,1000),
	                	'btypeid'=>1
	        		);
		        	$buyer=new CBuyer();
		        	$uid = $buyer->create($commonData,$buyerData);
		        	if(is_numeric($uid)) {
		        		session_start();
		        		$_SESSION['uid'] = $uid;
		        		setcookie(COOKIE_PRE.'uid', $uid ,null,'/');		        		
		        	} else {
		        		echo 0;
		        		exit();
		        	}
	        	}
            }
        } else {
        	$this->view->hasLog = 1;
        }      
        
        if (empty($_COOKIE[COOKIE_PRE . 'uid'])) {
        	if (isset($_SESSION['uid'])) {
        		$uid = $_SESSION['uid'];
        	} else {
        		echo 0;
        		exit();
        	}
        } else {
        	$uid = $_COOKIE[COOKIE_PRE . 'uid'];
        }
        $addressId = 0;
        $addressTable = new CAddress();		
        $isLog = 1;   
        if ($this->getRequest()->isPost()) {
        	if ($this->getRequest()->getParam('id') == 0) {      		
		    	$name = $this->getRequest()->getParam('name');
//		    	$zip = $this->getRequest()->getParam('zip');
		    	$address = $this->getRequest()->getParam('address');
		    	$addressExtra = $this->getRequest()->getParam('address_extra');
		    	$state = $this->getRequest()->getParam('state');
		    	$city = $this->getRequest()->getParam('city');
		    	$phone = $this->getRequest()->getParam('phone');
		    	$postCode = $this->getRequest()->getParam('post_code');
		    	$isLog = $this->getRequest()->getParam('islog');
		    	$email = $this->getRequest()->getParam('email');	    		     	
		    	if ( empty($name) || empty($address)
		    		|| empty($state) || empty($city) || empty($phone) || empty($postCode)) {
		    		$this->getHelper('viewRenderer')->setNoRender();
            		echo '1'; //Please Full The Input	    		
		    		return;
		    	}		    	 	
		    	$row = array('name'=>$name,
		    				 'uid'=>$uid,
		    				 'content'=>$address . ' ' . $addressExtra,
		    				 'location_id'=>$state,
		    			     'city'=>$city,
		    				 'state'=>$this->getRequest()->getParam('state1'),
		    				 'phone'=>$phone,
		    				 'post_code'=>$postCode,
		    				 'email'=>$email,
		    				 'add_time'=>time()
		    				 );		    	
		    	$addressId = $addressTable->insert($row);
		    }
        } else {
        	if (!$addressId) {
	        	$addressId = intval($this->getRequest()->getParam('id'));
	        } 
        }
        //没有地址
        if ($addressId == 0) {
        	$this->getHelper('viewRenderer')->setNoRender();
            echo '2';
            return;
        }
        
        $address = $addressTable->getDetail($addressId);
        if (empty($address)) {
        	$this->getHelper('viewRenderer')->setNoRender();
            echo '2';
            return;
        }      
        $user = $member->getUserDetails(array('uid'=>$uid));  
        $contactRow = $address[0];
        unset($contactRow['addressid']);
        //$contactRow['email'] = $user[0]['email'];
        
        $contact = new COrderContact();
        $contactid = $contact->createContact($contactRow);
        
        if ($isLog != 1) {
        	$addressTable->delete('addressid = ' . $addressId);
        }   
		
       // $this->_redirect('product-ship?id=' . $contactid);  
        $id = $contactid;     
        $contactTable  = new COrderContact();
        $contact = $contactTable->getUserContact($id, $uid);
        
        if (count($contact) == 0) {
        	echo '3'; //Error Address
        	return;
        }  
        $this->view->contactid = $id;
        $CFenlei = new CFenlei("location");
        $onelocationArray = $CFenlei->getoneFenlei($contact[0]['location_id']);
        $Cyunfei = new Cyunfei();
        $yunfeiArray = $Cyunfei->getyunfeiIN($onelocationArray[0]['yunfei']);
        $this->view->yunfeiArray = $yunfeiArray; 
        $yunfei = array();
        if ($yunfeiArray) {
	        foreach ($yunfeiArray as $v) {
	        	if ($v['openflag']) {
	        		$yunfei[] = $v;
	        	}
	        }
        }
        $this->view->yunfeiJs = json_encode($yunfei);
        $array = $this->getHelper('Item')->getOrderItemArray();        
        $totalPrice = $array['totalPrice'];
        $this->view->totalPrice = $totalPrice; 
        //积分支付
        $flashCommon = new CFlashcommon();        
        $creditAmount = $flashCommon->getAvaiAmount($uid);
		if($creditAmount >= $totalPrice/5) {
			$this->view->canUseCredit = 1;
		} else {
			$this->view->canUseCredit = 0;
		}
		$this->view->creditAmount = $creditAmount;
		
        $this->view->disSave = $array['totalPriceDisSave'];
        
        $user = $member->getUserDetails(array('uid'=>$uid));
        $score = new CScore();
        $userDollar = $score->score2dollar($user[0]['integral']);
        if ($userDollar >= $totalPrice) {
        	$this->view->useDollar = $totalPrice;
        } else {
        	$this->view->useDollar = $userDollar;
        }
        $this->view->userDollar = $userDollar;
        /**
         * 活动添加的代码
         */
        $totalAmount = 0;
        $i = 0;
        $fitstTwoPrice = 0;
        foreach ($this->view->itemArray as $v) {
        	$totalAmount += $v['amounts'];
        	if ($i < 2) {
        		$firstTwoPrice += $v['net_price'];
        	}
        	$i++;
        }	
		if (count($this->view->itemArray) == 1) {
			$firstTwoPrice = $this->view->itemArray[0]['net_price']*2 ;
		}       
        $game = new CGame();
		$oldUseDollar = $this->view->useDollar;
        if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {
	        if ($totalAmount <= 2) {
	        	$this->view->shouldPay = 0;		   
	        	$this->view->useDollar = $totalAmount;
	        } else {
	        	$this->view->shouldPay = 1;
	        	$this->view->useDollar = $firstTwoPrice;
	        }
	        $this->view->validatePrize = 1;
	        //$this->view->totalPrice = $totalPrice - $this->view->useDollar;
        } else {        
        	$this->view->shouldPay = 1;
        	$this->view->validatePrize = 0;
        }	      
		if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
           $this->view->shouldPay = 1;
		   $this->view->validatePrize = 0;
		   $this->view->useDollar = $oldUseDollar;
        }  	        
        /**end*/
        $this->view->addressId = $addressId;
        //sns
    	$memberattr = new CMemberattr();
		$row = $memberattr->getAttr('facebook', $uid);
		if ($row) {
			$this->view->facebook = $row->attr_value;
		} else {
			$this->view->facebook = '';
		}
		
        $row = $memberattr->getAttr('twitter', $uid);
		if ($row) {
			$this->view->twitter = $row->attr_value;
		} else {
			$this->view->twitter = '';
		}
    }
    
	public function payorder1Action()
    {
    	$this->getHelper('layout')->disableLayout();
    	$this->view->styleName = 'order';
    	$this->view->webSiteTitle = 'Pay My Order';
    	$this->view->webSiteKeywords = 'Pay My Order';
    	$this->view->webSiteDescription = 'Pay My Order';
    	$orderid = $this->getRequest()->getParam('orderid');
    	$member = new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
        } else {
        	$this->view->hasLog = 1;
        }      
        
        if (empty($_COOKIE[COOKIE_PRE . 'uid'])) {
        	if (isset($_SESSION['uid'])) {
        		$uid = $_SESSION['uid'];
        	} else {
        		echo 0;
        		exit();
        	}
        } else {
        	$uid = $_COOKIE[COOKIE_PRE . 'uid'];
        }
        $addressId = 0;
        $addressTable = new CAddress();		
        $isLog = 1;   
        if ($this->getRequest()->isPost()) {
        	if ($this->getRequest()->getParam('id') == 0) {      		
		    	$name = $this->getRequest()->getParam('name');
//		    	$zip = $this->getRequest()->getParam('zip');
		    	$address = $this->getRequest()->getParam('address');
		    	$addressExtra = $this->getRequest()->getParam('address_extra');
		    	$state = $this->getRequest()->getParam('state');
		    	$city = $this->getRequest()->getParam('city');
		    	$phone = $this->getRequest()->getParam('phone');
		    	$postCode = $this->getRequest()->getParam('post_code');
		    	$isLog = $this->getRequest()->getParam('islog');
		    	$email = $this->getRequest()->getParam('email');	    		     	
		    	if ( empty($name) || empty($address)
		    		|| empty($state) || empty($city) || empty($phone) || empty($postCode)) {
		    		$this->getHelper('viewRenderer')->setNoRender();
            		echo '1'; //Please Full The Input	    		
		    		return;
		    	}		    	 	
		    	$row = array('name'=>$name,
		    				 'uid'=>$uid,
		    				 'content'=>$address . ' ' . $addressExtra,
		    				 'location_id'=>$state,
		    			     'city'=>$city,
		    				 'state'=>$this->getRequest()->getParam('state1'),
		    				 'phone'=>$phone,
		    				 'post_code'=>$postCode,
		    				 'email'=>$email,
		    				 'add_time'=>time()
		    				 );		    	
		    	$addressId = $addressTable->insert($row);
		    }
        } else {
        	if (!$addressId) {
	        	$addressId = intval($this->getRequest()->getParam('id'));
	        } 
        }
        //没有地址
        if ($addressId == 0) {
        	$this->getHelper('viewRenderer')->setNoRender();
            echo '2';
            return;
        }
        
        $address = $addressTable->getDetail($addressId);
        if (empty($address)) {
        	$this->getHelper('viewRenderer')->setNoRender();
            echo '2';
            return;
        }      
        $user = $member->getUserDetails(array('uid'=>$uid));  
        $contactRow = $address[0];
        unset($contactRow['addressid']);
        //$contactRow['email'] = $user[0]['email'];
        
        $contact = new COrderContact();
        $contactid = $contact->createContact($contactRow);
        
        if ($isLog != 1) {
        	$addressTable->delete('addressid = ' . $addressId);
        }   
		
       // $this->_redirect('product-ship?id=' . $contactid);  
        $id = $contactid;     
        $contactTable  = new COrderContact();
        $contact = $contactTable->getUserContact($id, $uid);
        
        if (count($contact) == 0) {
        	echo '3'; //Error Address
        	return;
        }  
        $this->view->contactid = $id;
        $CFenlei = new CFenlei("location");
        $onelocationArray = $CFenlei->getoneFenlei($contact[0]['location_id']);
        $Cyunfei = new Cyunfei();
        $yunfeiArray = $Cyunfei->getyunfeiIN($onelocationArray[0]['yunfei']);
        $this->view->yunfeiArray = $yunfeiArray; 
        $yunfei = array();
        if ($yunfeiArray) {
	        foreach ($yunfeiArray as $v) {
	        	if ($v['openflag']) {
	        		$yunfei[] = $v;
	        	}
	        }
        }
        $this->view->yunfeiJs = json_encode($yunfei);
        $order = new COrder();
    	$orderDetail = $order->getDetail($orderid);
            
        if($orderDetail[0]['uid'] != $_COOKIE[COOKIE_PRE.'uid']) {
            exit();
        }
            
        $totalPrice = $orderDetail[0]['money'] + $orderDetail[0]['coupon'] ;
        if ($orderDetail[0]['usememberdiscount']) {
           $totalPrice += MEMBER_DOLLAR;
        }  
    	//积分支付
        $flashCommon = new CFlashcommon();        
        $creditAmount = $flashCommon->getAvaiAmount($uid);
		if($creditAmount >= $totalPrice/5) {
			$this->view->canUseCredit = 1;
			$this->view->creditAmount = $creditAmount;
		} else {
			$this->view->canUseCredit = 0;
		}
        
	    $totalPrice -= $orderDetail[0]['yunfeiprice'];
        
        $this->view->totalPrice = $totalPrice;        
        
        $user = $member->getUserDetails(array('uid'=>$uid));
        $score = new CScore();
        $userDollar = $score->score2dollar($user[0]['integral']);
        if ($userDollar >= $totalPrice) {
        	$this->view->useDollar = $totalPrice;
        } else {
        	$this->view->useDollar = $userDollar;
        }
        $this->view->userDollar = $userDollar;   
        $this->view->shouldPay = 1;    
        $this->view->orderid = $orderid; 
        $this->view->yunfeiid = $orderDetail[0]['yunfeiid'];
        $this->view->addressId = $addressId;
        
    	//sns
    	$memberattr = new CMemberattr();
		$row = $memberattr->getAttr('facebook', $uid);
		if ($row) {
			$this->view->facebook = $row->attr_value;
		} else {
			$this->view->facebook = '';
		}
		
        $row = $memberattr->getAttr('twitter', $uid);
		if ($row) {
			$this->view->twitter = $row->attr_value;
		} else {
			$this->view->twitter = '';
		}
    }
    
    public function shipAction()
    {
    	unset($_SESSION['uid']);
    	$this->view->styleName = 'order';
    	$this->view->webSiteTitle = 'Select Ship';
    	$this->view->webSiteKeywords = 'Select Ship';
    	$this->view->webSiteDescription = 'Select Ship';
    	$id = intval($this->getRequest()->getParam('id'));
    	
    	$member=new CMember();
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipp-id=' . $id);
            return;
        }
    	
    	$contactTable  = new COrderContact();
        $contact = $contactTable->getUserContact($id, $_COOKIE[COOKIE_PRE . 'uid']);
        
        if (count($contact) == 0) {
        	$this->_redirect('/product-addcontact');
        	return;
        }  
        $this->view->contactid = $id;
        $CFenlei = new CFenlei("location");
        $onelocationArray = $CFenlei->getoneFenlei($contact[0]['location_id']);
        $Cyunfei = new Cyunfei();
        $yunfeiArray = $Cyunfei->getyunfeiIN($onelocationArray[0]['yunfei']);
        $this->view->yunfeiArray = $yunfeiArray;
    }
    
    public function doshipAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	$this->getHelper('layout')->disableLayout();
    	if (!$this->_request->isPost()) {
            $this->_redirect(MY_URL);
            return false;
        }
        $member=new CMember();
        if ( 1== 2) {
            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipping');
        } else {
            $contactid = $this->_request->getParam('contactid');
            $yunfeiid = $this->_request->getParam('yunfeiids');
            $payAction = $this->getRequest()->getParam('payment_action');   
            $email = $this->getRequest()->getParam('paypal_email');
            
            $useCoupon = $this->getRequest()->getParam('usecoupon');            
            $useCouponCode = $this->getRequest()->getParam('usecouponcode');
            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
            $score = new CScore();
            $userDollar = $score->score2dollar($user[0]['integral']); 
            $game = new CGame();
            if (!empty($useCoupon) && !$game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {            	
	            if (!preg_match('/^\d+(\.\d+)?/', $useCoupon) || ($useCoupon > $userDollar && !$useCouponCode)) { //积分是否合法
	            	$this->_redirect('/product-addcontact');
		        	return;
	            }	            
            } 

            if ($payAction == 'pay-credit') {
            	$useCoupon = 0;
            }
           
            
            //验证地址是否合法
            $contactTable  = new COrderContact();
	        $contact = $contactTable->getUserContact($contactid, $_COOKIE[COOKIE_PRE . 'uid']);
	        	        
	        if (count($contact) == 0) {
	        	$this->_redirect('/product-addcontact');
	        	return;
	        }  
            
            $Cyunfei=new Cyunfei();
            $oneyunfeiArray = array();
            if ($yunfeiid) {
                $oneyunfeiArray = $Cyunfei->getDetail($yunfeiid);
            }
            $array = $this->getHelper('Item')->getOrderItemArray();
            $itemArray = $array['itemArray'];
            if (empty($itemArray) || !isset($itemArray[0]['itemid'])) {
            	$this->_redirect('/product-addcontact');
		        return;
            }
            
            $totalPrice = $array['totalPrice'];
            foreach ($itemArray as &$value) {
                unset($value['content']);
                unset($value['pattern_intro']);
            }
            
        	if ($useCoupon > 0) {
            	$totalPrice -= $useCoupon;     //应付金额  
//            	$useScore = $score->dollar2score($useCoupon);
//            	//减去积分
//            	if (!$useCouponCode){
//	            	$member->updateIntegral($useScore, $_COOKIE[COOKIE_PRE.'uid']);
//			    	$fenlei = new CFenlei('product');
//			    	$fenlei->refreshIntegral();
//            	}     	
            }    
            
		    if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
		        $useMemberDiscount = 0;
		    } else {
		    	$useMemberDiscount = 1;
		    	$game = new CGame();
		    	if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {
		    		$totalPrice = $totalPrice;
		    	} else {
		    		$totalPrice = $totalPrice - MEMBER_DOLLAR;
		    	}
		    }
		    
        	if (defined('SELL_VALIDATE')) {
            	$totalPrice = $totalPrice * (1-SELL_OFF);
            }

            if ($oneyunfeiArray[0]["price"]) {
                $totalPrice = $totalPrice+ $oneyunfeiArray[0]["price"];
            }           
            if($oneyunfeiArray) {
                $yunfeiprice = $oneyunfeiArray[0]["price"];
            } else {
                $yunfeiprice = 0;
                $yunfeiid = 0;
            }
            
            $order=new COrder();
            $data=array(
                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
                'add_time'=>time(),
                'seller_uid'=>1,
                'money'=>$totalPrice,
            	'coupon'=>$useCoupon,
                'order_string'=>serialize($itemArray),
                'delivery_days'=>0,
                'lagnappe'=>0,
                'LagnappeMesg'=>'',
                'yunfeiid'=> $yunfeiid,
                'yunfeiprice'=> $yunfeiprice,
                'contactid'=> $contactid,
                'ieinfo'=> $_SERVER[HTTP_USER_AGENT],
            	'cart_session_id'=>$_COOKIE[COOKIE_PRE . 'product_buy_session'],
                'flid'=>1,
            	'usecouponcode'=>$useCouponCode,
            	'usememberdiscount'=>$useMemberDiscount,
            	'msg'=>isset($_COOKIE['msg']) ? urldecode($_COOKIE['msg']) : ''
            );
            
            switch($payAction) {
            	case 'pay-paypal':
            		$data['fee_rate'] = PAYPAL_RATE;
            		break;
            	case 'pay-ssfkh':
            		$data['fee_rate'] = CE_SSFKH;
            		break;
            	case 'pay-nopassssfkh':
            		$data['fee_rate'] = CE_SSFKHNOPASS;
            		break;
            }
            $orderid = $order->createOrder($data);
	        //用户存在该坑位
	        $uid = isset($_COOKIE[COOKIE_PRE . 'uid']) ? $_COOKIE[COOKIE_PRE . 'uid'] : 0;       
        	$flashCommon = new CFlashcommon();
            foreach($itemArray as $v) {    
            	if ($flashCommon->isUserFlashItem($uid, $v['itemid']) ) {
            		$flashItem = new CFlashitem();
            		$flashItem->update(array('statu'=>0), 'uid = ' . $uid . ' and itemid=' . $v['itemid']);
            	}
            	if ($flashCommon->isUserWhenEverFlashItem($uid, $v['itemid']) ) {
            		$flashItem = new CFlashwheneveritem();
            		$flashItem->update(array('statu'=>0), 'uid = ' . $uid . ' and itemid=' . $v['itemid']);
            	}
            }
            //
            if (defined('SELL_VALIDATE')) {
            	$buyModel = new CPyramidMemberBuy();
            	$buyModel->add(array('facebook_id'=>$_COOKIE[COOKIE_PRE.'my_facebook_id'], 'from_facebook_id'=>$_COOKIE[COOKIE_PRE.'inv_facebook_id'],
            						 'order_id'=>$orderid, 'order_amount'=>$data['money'], 'add_time'=>time()));
            }
            //sns
            $sns = $this->getRequest()->getParam('sns', '');
            $snsValue = $this->getRequest()->getParam($sns);
            if ($sns && $snsValue) {
            	$memberAttr = new CMemberattr();
            	$memberAttr->updateSns($sns, $snsValue, $uid);
            }
            if ($payAction == "pay-ssfkh1") {
            	session_start();
            	$bAddress = $this->getRequest()->getParam('Address');
		        $bCity = $this->getRequest()->getParam('City');
		        $bState = $this->getRequest()->getParam('State');
		        $bZip = $this->getRequest()->getParam('Zip');
		        $bCountry = $this->getRequest()->getParam('Country');
		        $bEmail = $this->getRequest()->getParam('Email');
		        $bPhone = $this->getRequest()->getParam('Phone');
		        
		        $cardNo = $this->getRequest()->getParam('cardNo');
		        $cvv2 = $this->getRequest()->getParam('cvv2');
		        $cardExpireMonth = $this->getRequest()->getParam('cardExpireMonth');
		        $cardExpireYear = $this->getRequest()->getParam('cardExpireYear');
		        $IssuingBank = $this->getRequest()->getParam('IssuingBank');
		        $firstName = $this->getRequest()->getParam('firstName');
		        $lastName = $this->getRequest()->getParam('lastName');
		        
		        $_SESSION['Address'] = $bAddress;
		        $_SESSION['City'] = $bCity;
		        $_SESSION['State'] = $bState;
		        $_SESSION['Zip'] = $bZip;
		        $_SESSION['Country'] = $bCountry;
		        $_SESSION['Email'] = $bEmail;
		        $_SESSION['Phone'] = $bPhone;
		        
		        $_SESSION['cardNo'] = $cardNo;
		        $_SESSION['cvv2'] = $cvv2;
		        $_SESSION['cardExpireMonth'] = $cardExpireMonth;
		        $_SESSION['cardExpireYear'] = $cardExpireYear;
		        $_SESSION['IssuingBank'] = $IssuingBank;
		        $_SESSION['firstName'] = $firstName;
		        $_SESSION['lastName'] = $lastName;
		        $payAction = "pay-ssfkh2";
            }
            $this->_redirect(MY_URL.'/' . $payAction . '?id=' . $orderid . '&email=' . $email);
        }
    }
    
	public function doship1Action()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	$this->getHelper('layout')->disableLayout();
    	if (!$this->_request->isPost()) {
            $this->_redirect(MY_URL);
            return false;
        }
        $member=new CMember();
        if ( 1== 2) {
            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipping');
        } else {
            $contactid = $this->_request->getParam('contactid');
            $yunfeiid = $this->_request->getParam('yunfeiids');
            $payAction = $this->getRequest()->getParam('payment_action');   
            $email = $this->getRequest()->getParam('paypal_email');
            $orderid = $this->getRequest()->getParam('orderids');
            
            $useCoupon = $this->getRequest()->getParam('usecoupon');            
            $useCouponCode = $this->getRequest()->getParam('usecouponcode');
            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
            $score = new CScore();
            $userDollar = $score->score2dollar($user[0]['integral']); 
            $game = new CGame();
            if (!empty($useCoupon) && !$game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {            	
	            if (!preg_match('/^\d+(\.\d+)?/', $useCoupon) || ($useCoupon > $userDollar && !$useCouponCode)) { //积分是否合法
	            	$this->_redirect('/product-addcontact');
		        	return;
	            }	            
            }          
           
            
            //验证地址是否合法
            $contactTable  = new COrderContact();
	        $contact = $contactTable->getUserContact($contactid, $_COOKIE[COOKIE_PRE . 'uid']);
	        	        
	        if (count($contact) == 0) {
	        	$this->_redirect('/product-addcontact');
	        	return;
	        }  
            
            $Cyunfei=new Cyunfei();
            $oneyunfeiArray = array();
            if ($yunfeiid) {
                $oneyunfeiArray = $Cyunfei->getDetail($yunfeiid);
            }        	           
            if($oneyunfeiArray) {
                $yunfeiprice = $oneyunfeiArray[0]["price"];
            } else {
                $yunfeiprice = 0;
                $yunfeiid = 0;
            }
            
            $order = new COrder();
            $orderDetail = $order->getDetail($orderid);
            
        	$totalPrice = $orderDetail[0]['money'] + $orderDetail[0]['coupon'] ;
	        if ($orderDetail[0]['usememberdiscount']) {
	           $totalPrice += MEMBER_DOLLAR;
	        } 
        	if ($payAction == 'pay-credit') {
            	$useCoupon = 0;
            }
	        $totalPrice -= MEMBER_DOLLAR;
	        $totalPrice -= $orderDetail[0]['yunfeiprice'];
	        $totalPrice -= $useCoupon;
        	if ($oneyunfeiArray[0]["price"]) {
                $totalPrice = $totalPrice+ $oneyunfeiArray[0]["price"];
            }
            
            $data=array(
                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],                
                'money'=>$totalPrice,
            	'coupon'=>$useCoupon,               
                'yunfeiid'=> $yunfeiid,
                'yunfeiprice'=> $yunfeiprice,
                'contactid'=> $contactid,
                'ieinfo'=> $_SERVER[HTTP_USER_AGENT],
            	'cart_session_id'=>$_COOKIE[COOKIE_PRE . 'product_buy_session'],
                'flid'=>1,
            	'usecouponcode'=>$useCouponCode,
            	'usememberdiscount'=>1
            );
            
            switch($payAction) {
            	case 'pay-paypal':
            		$data['fee_rate'] = PAYPAL_RATE;
            		break;
            	case 'pay-ssfkh':
            		$data['fee_rate'] = CE_SSFKH;
            		break;
            	case 'pay-nopassssfkh':
            		$data['fee_rate'] = CE_SSFKHNOPASS;
            		break;
            }
            $order->editOrder($orderid, $data);            
            
        	//sns
        	$uid = $_COOKIE[COOKIE_PRE.'uid'];
            $sns = $this->getRequest()->getParam('sns', '');
            $snsValue = $this->getRequest()->getParam($sns);
            if ($sns && $snsValue) {
            	$memberAttr = new CMemberattr();
            	$memberAttr->updateSns($sns, $snsValue, $uid);
            }
            if ($payAction == "pay-ssfkh1") {
            	session_start();
            	$bAddress = $this->getRequest()->getParam('Address');
		        $bCity = $this->getRequest()->getParam('City');
		        $bState = $this->getRequest()->getParam('State');
		        $bZip = $this->getRequest()->getParam('Zip');
		        $bCountry = $this->getRequest()->getParam('Country');
		        $bEmail = $this->getRequest()->getParam('Email');
		        $bPhone = $this->getRequest()->getParam('Phone');
		        
		        $cardNo = $this->getRequest()->getParam('cardNo');
		        $cvv2 = $this->getRequest()->getParam('cvv2');
		        $cardExpireMonth = $this->getRequest()->getParam('cardExpireMonth');
		        $cardExpireYear = $this->getRequest()->getParam('cardExpireYear');
		        $IssuingBank = $this->getRequest()->getParam('IssuingBank');
		        $firstName = $this->getRequest()->getParam('firstName');
		        $lastName = $this->getRequest()->getParam('lastName');
		        
		        $_SESSION['Address'] = $bAddress;
		        $_SESSION['City'] = $bCity;
		        $_SESSION['State'] = $bState;
		        $_SESSION['Zip'] = $bZip;
		        $_SESSION['Country'] = $bCountry;
		        $_SESSION['Email'] = $bEmail;
		        $_SESSION['Phone'] = $bPhone;
		        
		        $_SESSION['cardNo'] = $cardNo;
		        $_SESSION['cvv2'] = $cvv2;
		        $_SESSION['cardExpireMonth'] = $cardExpireMonth;
		        $_SESSION['cardExpireYear'] = $cardExpireYear;
		        $_SESSION['IssuingBank'] = $IssuingBank;
		        $_SESSION['firstName'] = $firstName;
		        $_SESSION['lastName'] = $lastName;
		        $payAction = "pay-ssfkh2";
            }
            $this->_redirect(MY_URL.'/' . $payAction . '?id=' . $orderid . '&email=' . $email);
        }
    }
    /**
     * 领取奖品
     */
	public function doshipfreeAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	
    	if (!$this->_request->isPost()) {
            $this->_redirect(MY_URL);
            return false;
        }
        $member=new CMember();
		  
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipping');
        } else {
        	$game = new CGame();
	        if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {
		        
	        } else {
	        	$this->_redirect(MY_URL);
            	return false;
	        }	    
            $contactid = $this->_request->getParam('contactid');
            $yunfeiid = $this->_request->getParam('yunfeiids');
            $payAction = $this->getRequest()->getParam('payment_action');   
            $email = $this->getRequest()->getParam('paypal_email');
 
            $useCoupon = $this->getRequest()->getParam('usecoupon');
    
            $useCouponCode = $this->getRequest()->getParam('usecouponcode');
            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
             
           
            
            //验证地址是否合法
            $contactTable  = new COrderContact();
	        $contact = $contactTable->getUserContact($contactid, $_COOKIE[COOKIE_PRE . 'uid']);
	        	        
	        if (count($contact) == 0) {
	        	$this->_redirect('/product-addcontact');
	        	return;
	        }  
            
            $Cyunfei=new Cyunfei();
            $oneyunfeiArray = array();
            if ($yunfeiid) {
                $oneyunfeiArray = $Cyunfei->getDetail($yunfeiid);
            }
            $array = $this->getHelper('Item')->getOrderItemArray();
            $itemArray = $array['itemArray'];
            
            if (empty($itemArray) || !isset($itemArray[0]['itemid'])) {
            	$this->_redirect('/product-addcontact');
		        return;
            }
            
            $totalPrice = $array['totalPrice'];
            foreach ($itemArray as &$value) {
                unset($value['content']);
                unset($value['pattern_intro']);
            }

            if ($oneyunfeiArray[0]["price"]) {
                $totalPrice = $totalPrice+ $oneyunfeiArray[0]["price"];
            }           
            if($oneyunfeiArray) {
                $yunfeiprice = $oneyunfeiArray[0]["price"];
            } else {
                $yunfeiprice = 0;
                $yunfeiid = 0;
            }
            
            $useMemberDiscount = 0; 
            
            $totalAmount = 0;
	        $i = 0;
	        $fitstTwoPrice = 0;
	        foreach ($this->view->itemArray as $v) {
	        	$totalAmount += $v['amounts'];
	        	if ($i < 2) {
	        		$firstTwoPrice += $v['net_price'];
	        	}
	        	$i++;
	        }	    
			if (count($this->view->itemArray) == 1) {
				$firstTwoPrice = $this->view->itemArray[0]['net_price']*2 ;
			}   
	        $game = new CGame();
	        if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {
		        if ($totalAmount <= 2) {
		        	$useCoupon = $this->view->totalPriceOrg;
		        } else {
		        	$useCoupon = $firstTwoPrice;
		        }		        
	        }	        
			$totalPrice = $totalPrice - $useCoupon;
            $order=new COrder();
            $data=array(
                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
                'add_time'=>time(),
                'seller_uid'=>1,
                'money'=>$totalPrice,
            	'coupon'=>$useCoupon,
                'order_string'=>serialize($itemArray),
                'delivery_days'=>0,
                'lagnappe'=>0,
                'LagnappeMesg'=>'',
                'yunfeiid'=> $yunfeiid,
                'yunfeiprice'=> $yunfeiprice,
                'contactid'=> $contactid,
                'ieinfo'=> $_SERVER[HTTP_USER_AGENT],
            	'cart_session_id'=>$_COOKIE[COOKIE_PRE . 'product_buy_session'],
                'flid'=>1,
            	'usecouponcode'=>$useCouponCode,
            	'usememberdiscount'=>$useMemberDiscount
            );    
            
            $orderid = $order->createOrder($data);
            $order->editOrder($orderid, array('flid'=>3));
            $game->update(array('prize_order_id'=>$orderid, 'isprize'=>1), 'hashcode="' . $_COOKIE[COOKIE_PRE . 'prize_hash'].'"');
            $this->view->showMsg('You will get the jerseys', '/adminb-order');
        }
    }
    
    public function addaddressAction()
    {
    	$this->getHelper('viewRenderer')->setNorender();
    	$this->getHelper('layout')->disableLayout();
    	
    }

    public function tipAction()
    {
    	$this->view->styleName = 'login';
    	$member = new CMember();
    	$this->view->webSiteTitle = 'You haven\'t login in! Please Select and continue to buy!';
    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
    		$couponCode = $this->getRequest()->getParam('code');
    		$this->view->code= $couponCode;
    	} else {
    		$useCoupon = $this->getRequest()->getParam('coupon');
    		$this->_redirect('/product-addcontact?coupon=' . $useCoupon);
    	}
    	$this->view->noLongBanner = 1;
    }
    
    public function addcontactAction()
    {
    	$this->view->styleName = 'order';
    	$this->view->webSiteTitle = 'Pay My Order';
    	$this->view->webSiteKeywords = 'Pay My Order';
    	//$this->view->webSiteDescription = 'Pay My Order';
    	$array = $this->getHelper('Item')->getOrderItemArray();
    	
    	/**
    	 * 
    	 * 下订单行为分析
    	 */
        $array = $this->getHelper('Item')->getOrderItemArray();
        $itemArray = $array['itemArray'];
        $logArray = $itemArray;
        foreach ($logArray as &$v) {        	
        	unset($v['content']);
        }
        $orderLog = new COrderlog();
        $orderLog->insert(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid'], 'ip'=>$_SERVER['REMOTE_ADDR'], 'order_str'=>addslashes(serialize($logArray)), 'addtime'=>date('Y-m-d H:i:s', time())));
		
        /**
         * end
         * 
         */
        $member = new CMember();
        $useCouponCode = 0;
        $useCoupon = 0;
        $userDollar = 0;
        if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            //$this->_redirect(MY_URL.'/auth-login?preurl=product-addcontact'); 不是登录的用户
            $location=new CFenlei('location');
            $location->setOrder('en_flname ASC');
            $fenleiArray=$location->getFenleiByPid(0);
            $this->view->assign('fenleiArray',$fenleiArray);            
            if (isset($_SESSION['uid'])) {
            	$uid = $_SESSION['uid'];
            	setcookie(COOKIE_PRE.'uid', $_SESSION['uid'] ,null,'/');
            } else {
            	$uid = 0;
            	setcookie(COOKIE_PRE.'uid', '' ,null,'/');
            }
            //使用优惠码，不用了
//	        $coupon = new CCouponCode();
//	        $couponCode = $this->getRequest()->getParam('code');
//			if (!empty($couponCode)) {
//				if ($row = $coupon->isexist($couponCode)) { //存在该优惠码
//					if (!$coupon->isexpires($couponCode)) { //优惠码未过期
//						$useCoupon = COUPON_DOLLAR;
//						$useCouponCode = 1;
//					} else {
//						$this->getHelper('viewRenderer')->setNoRender();
//						$this->view->showMsg('The coupon code you input has expired!');
//		            	return false;
//					}
//				} else {
//					$this->getHelper('viewRenderer')->setNoRender();
//					$this->view->showMsg('The coupon code you input is wrong!');
//		            return false;
//				}
//			}
        } else {        	
        	//使用积分
       		$useCoupon = $this->getRequest()->getParam('coupon');
            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
            $score = new CScore();
            $userDollar = $score->score2dollar($user[0]['integral']);
            //直接使用默认积分
//            if (!empty($useCoupon)) {            	
//	            if (!preg_match('/^\d+(\.\d+)?/', $useCoupon) || $useCoupon > $userDollar) { //积分是否合法
//	            	$this->_redirect('/product-showitem');
//		        	return;
//	            }	            
//            }
	        $totalPrice = $array['totalPrice'];
	        
	        /**
	         * 活动添加的代码
	         */
	        $totalAmount = 0;
	        $i = 0;
	        $fitstTwoPrice = 0;
	        foreach ($this->view->itemArray as $v) {
	        	$totalAmount += $v['amounts'];
	        	if ($i < 2) {
	        		$firstTwoPrice += $v['net_price'];
	        	}
	        	$i++;
	        }	       
			if (count($this->view->itemArray) == 1) {
				$firstTwoPrice = $this->view->itemArray[0]['net_price']*2 ;
			}  
	        $game = new CGame();
	        if ($game->isValidate($_COOKIE[COOKIE_PRE . 'prize_hash'])) {
		        if ($totalAmount <= 2) {
		        	$useCoupon = $totalAmount;
		        } else {
		        	$useCoupon = $firstTwoPrice;
		        }
		        $this->view->validatePrize = 1;
		        $this->view->totalPrice = $totalPrice - $this->view->useDollar;
	        } else {        
	        	$this->view->shouldPay = 1;
	        	$this->view->validatePrize = 0;
	        }	        	        
	        /**end*/
	        if ($this->view->validatePrize) {
	        	$amount = $totalPrice;
	        } else {
		        $amount = $totalPrice - MEMBER_DOLLAR;
		        $amount = $amount - 1;	 
		        if ($userDollar >= $amount && $amount > 0) {
				    $useCoupon = $amount;
				} else {
				    $useCoupon = $userDollar;
				}     
	        }  
	    	
			
			if ($amount < 0) {
				$useCoupon = 0;
			}
			
            $contact=new COrderContact();
            //取得该用户所有地址
            $contactArray=$contact->getAllContacts(0,0,$_COOKIE[COOKIE_PRE.'uid']);
            //地区信息
            $location=new CFenlei('location');
            $location->setOrder('en_flname ASC');
            $fenleiArray=$location->getFenleiByPid(0);

            $this->view->assign('fenleiArray',$fenleiArray);
            $this->view->assign('contactArray',$contactArray);

            $address=new CAddress();
            
			//取得该用户所有地址
            $addressArray=$address->getAllAddresses($_COOKIE[COOKIE_PRE.'uid']);
            $this->view->assign('addressArray',$addressArray); 

            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE.'uid']));
        	$this->view->email = $user[0]['email'];
        	$uid = $_COOKIE[COOKIE_PRE.'uid'];
        	
        	$this->view->noLongBanner = 1;
        }   
        
        //验证购物车        
        $itemArray = $array['itemArray'];
        
        if (empty($itemArray) || !isset($itemArray[0]['itemid'])) {
        	$this->getHelper('viewRenderer')->setNoRender();
        	$this->view->showMsg('Error', '/product-showitem');
        	return;
        }       
        
        
        //验证是否全部促销
        $onsaleFlag = 0;
        foreach ($itemArray as $v) {
        	if ($v['onsales'] == 0) {
        		$onsaleFlag = 1;
        		break;
        	}
        }
        if ($onsaleFlag == 0) {
        	$this->getHelper('viewRenderer')->setNoRender();
        	$this->view->showMsg('You must choose other product not on discount at least one.', '/product-showitem');
        	return;
        }
        
        $this->view->useCoupon = $useCoupon;
        $this->view->useCouponCode = $useCouponCode;
        if (!empty($uid)) {
	        $address = new CAddress();
	        $addressArray=$address->getAllAddresses($uid);
	        $this->view->assign('addressArray',$addressArray); 
        } else {
        	$this->view->assign('addressArray',array());
        }
    }
    
	public function addcontact2Action()
    {
    	$this->view->styleName = 'order';
    	$this->view->webSiteTitle = 'Pay My Order';
    	$this->view->webSiteKeywords = 'Pay My Order';
    	//$this->view->webSiteDescription = 'Pay My Order';
    	
    	$id = $this->getRequest()->getParam('id');
    	$id = intval($id);
    	
    	$pmethod = $this->getRequest()->getParam('pmethod',0);
    	$this->view->pmethod = $pmethod;
    	
        $member = new CMember();       
        if ($member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName()) && $_COOKIE[COOKIE_PRE.'member_type']=='buyer') {
         
            $location=new CFenlei('location');
            $location->setOrder('en_flname ASC');
            $fenleiArray=$location->getFenleiByPid(0);
            $this->view->assign('fenleiArray',$fenleiArray);     

            $order = new COrder();
            $orderDetail = $order->getDetail($id);
            
            if($orderDetail[0]['uid'] != $_COOKIE[COOKIE_PRE.'uid']) {
            	exit();
            }
            
            $totalPrice = $orderDetail[0]['money'] + $orderDetail[0]['coupon'] ;
            if ($orderDetail[0]['usememberdiscount']) {
            	$totalPrice += MEMBER_DOLLER;
            }
            $totalPrice -= MEMBER_DOLLAR;
	        $totalPrice -= $orderDetail[0]['yunfeiprice'];
            $uid = $_COOKIE[COOKIE_PRE.'uid'];	
        	
        	
        	$contact=new COrderContact();
            //取得该用户所有地址
            $contactArray=$contact->getAllContacts(0,0,$_COOKIE[COOKIE_PRE.'uid']);
            //地区信息
            $location=new CFenlei('location');
            $location->setOrder('en_flname ASC');
            $fenleiArray=$location->getFenleiByPid(0);

            $this->view->assign('fenleiArray',$fenleiArray);
            $this->view->assign('contactArray',$contactArray);

            $address=new CAddress();
            
			//取得该用户所有地址
            $addressArray=$address->getAllAddresses($_COOKIE[COOKIE_PRE.'uid']);
            $this->view->assign('addressArray',$addressArray); 
            
            $orderContact = $contact->getDetail($orderDetail[0]['contactid']);
            foreach ($addressArray as $address_v) {
            	$tmpa = $address_v;
            	unset($tmpa['addressid']);
            	unset($tmpa['add_time']);
            	$tmpb = $orderContact[0];
            	           
            	unset($tmpb['contactid']);
            	unset($tmpb['add_time']);
            	sort($tmpa);
                sort($tmpb);            	
            	if ($tmpa == $tmpb) {
            		$this->view->selectAddress = $address_v['addressid'];
            		break;
            	}
            }

            $user = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE.'uid']));
        	$this->view->email = $user[0]['email'];
        	$uid = $_COOKIE[COOKIE_PRE.'uid'];        	
        	
            $score = new CScore();
            $userDollar = $score->score2dollar($user[0]['integral']);
            
            $amount = $totalPrice - MEMBER_DOLLAR;
	        $amount = $amount - 1;	 
	        if ($userDollar >= $amount && $amount > 0) {
			    $useCoupon = $amount;
			} else {
			    $useCoupon = $userDollar;
			}
			
			$this->view->useCoupon = $useCoupon;
        	$this->view->useCouponCode = 0;
        	$this->view->orderid = $id;
        	$this->view->contactid = $orderDetail[0]['contactid'];
        }
        
        $this->view->noLongBanner = 1;
    }
    
    public function deleteaddressAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	$this->getHelper('layout')->disableLayout();
    	$address=new CAddress();
    	$id = intval($this->getRequest()->getParam('id'));
    	if ($address->deleteAddress($id, $_COOKIE[COOKIE_PRE . 'uid'])) {
    		echo 1;
    	} else {
    		echo 0;
    	}
    }
    
    public function updateaddressAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
    	$this->getHelper('layout')->disableLayout();
    	
    	$id = intval($this->getRequest()->getParam('id'));
    	$name = $this->getRequest()->getParam('name');
//    	$zip = $this->getRequest()->getParam('zip');
    	$address = $this->getRequest()->getParam('address');
    	$state = $this->getRequest()->getParam('state');
    	$city = $this->getRequest()->getParam('city');
    	$phone = $this->getRequest()->getParam('phone');
    	$postCode = $this->getRequest()->getParam('post_code');
    	$email = $this->getRequest()->getParam('email');
    	
    	if (empty($id) || empty($name) || empty($address)
    		|| empty($state) || empty($city) || empty($phone) || empty($postCode)) {
    		echo '0';
    		return;
    	}

    	$addressTable = new CAddress();
    	
    	$row = array('name'=>$name,
    				 'uid'=>$_COOKIE[COOKIE_PRE . 'uid'],
    				 'content'=>$address,
    				 'location_id'=>$state,
    			     'city'=>$city,
    			     'state'=>$this->getRequest()->getParam('state1'),
    				 'phone'=>$phone,
    				 'post_code'=>$postCode,
    				 'email'=>$email,
    				 'add_time'=>time()
    				 );

    	if ($addressTable->updateAddress($id, $_COOKIE[COOKIE_PRE . 'uid'], $row)) {
    		echo 1;
    	} else {
    		echo 0;
    	} 
    }
    
    public function paymoneyAction()
    {
    	$this->getHelper('layout')->disableLayout();
    	
    	if (!$this->getRequest()->isPost()) {
    		echo 'error';
    		return;
    	}
    	$contactid = $this->_request->getParam('contactid');
        $yunfeiid = $this->_request->getParam('yunfeiid');
            
        //验证地址是否合法
        $contactTable  = new COrderContact();
        $contact = $contactTable->getUserContact($contactid, $_COOKIE[COOKIE_PRE . 'uid']);
        
        if (count($contact) == 0) {
        	echo 'error';
        	return;
        }  
            
        $Cyunfei=new Cyunfei();
        $oneyunfeiArray = array();
        if ($yunfeiid) {
           $oneyunfeiArray = $Cyunfei->getDetail($yunfeiid);
        }
    	$array = $this->getHelper('Item')->getOrderItemArray();
        $itemArray = $array['itemArray'];
        $totalPrice = $array['totalPrice'];
        foreach ($itemArray as &$value) {
            unset($value['content']);
            unset($value['pattern_intro']);
        }

        if ($oneyunfeiArray[0]["price"]) {
            $totalPrice = $totalPrice+ $oneyunfeiArray[0]["price"];
        }
            
        if($oneyunfeiArray) {
           $yunfeiprice = $oneyunfeiArray[0]["price"];
        }
        
        $this->view->total = $totalPrice;
        $this->view->yunfeiid = $yunfeiid;
        $this->view->contactid = $contactid;        
    }
    
    public function getaddressAction()
    {    	   	
    	$this->getHelper('layout')->disableLayout();    	
    	$address=new CAddress();
    	$member=new CMember();
        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {
        	if (!empty($_SESSION['uid']) && ($_SESSION['uid'] == $_COOKIE[COOKIE_PRE.'uid'])) { //已经有空白帐户
        		
        	} else { //未登录也没空白帐户
        		$this->getHelper('viewRenderer')->setNoRender();
        		echo 0;
        		exit();
        	}
        }   		
//		if (!empty($_COOKIE[COOKIE_PRE.'uid'])) {
//			$uid = $_COOKIE[COOKIE_PRE.'uid'];
//		} elseif (isset($_GET['uid'])) {
//			$uid = intval($_GET['uid']);
//		} else {
//			$this->getHelper('viewRenderer')->setNoRender();
//        	echo 0;
//        	exit();			
//		}
		
		//取得该用户所有地址
		if(!empty($_SESSION['uid']) && ($_SESSION['uid'] == $_COOKIE[COOKIE_PRE.'uid'])){
        	$addressArray=$address->getAllAddresses($_SESSION['uid']);
		} elseif (!empty($_COOKIE[COOKIE_PRE.'uid'])) {
			$addressArray=$address->getAllAddresses($_COOKIE[COOKIE_PRE.'uid']);
		} else {
			echo 0;
			exit();
		}
        $this->view->assign('addressArray',$addressArray);        
        $location=new CFenlei('location');
        $location->setOrder('en_flname ASC');
        $fenleiArray=$location->getFenleiByPid(0);

        $this->view->assign('fenleiArray',$fenleiArray);
    }
    
	public function getaddress1Action()
    {    	   	
    	$this->getHelper('layout')->disableLayout();    	
    	$address=new CAddress();
    	$member=new CMember();
        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {
        	if (!empty($_SESSION['uid']) && ($_SESSION['uid'] == $_COOKIE[COOKIE_PRE.'uid'])) { //已经有空白帐户
        		
        	} else { //未登录也没空白帐户
        		$this->getHelper('viewRenderer')->setNoRender();
        		echo 0;
        		exit();
        	}
        }   		
//		if (!empty($_COOKIE[COOKIE_PRE.'uid'])) {
//			$uid = $_COOKIE[COOKIE_PRE.'uid'];
//		} elseif (isset($_GET['uid'])) {
//			$uid = intval($_GET['uid']);
//		} else {
//			$this->getHelper('viewRenderer')->setNoRender();
//        	echo 0;
//        	exit();			
//		}
		
		//取得该用户所有地址
		if(!empty($_SESSION['uid']) && ($_SESSION['uid'] == $_COOKIE[COOKIE_PRE.'uid'])){
        	$addressArray=$address->getAllAddresses($_SESSION['uid']);
		} elseif (!empty($_COOKIE[COOKIE_PRE.'uid'])) {
			$addressArray=$address->getAllAddresses($_COOKIE[COOKIE_PRE.'uid']);
		} else {
			echo 0;
			exit();
		}
        $this->view->assign('addressArray',$addressArray);        
        $location=new CFenlei('location');
        $location->setOrder('en_flname ASC');
        $fenleiArray=$location->getFenleiByPid(0);

        $this->view->assign('fenleiArray',$fenleiArray);
    }

    public function doaddcontactAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
        if(!$this->_request->isPost())
        {
            $this->_redirect(MY_URL);
            return false;
        }
        $member=new CMember();
        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {
            $this->_redirect(MY_URL.'/auth-login?preurl=product-addcontact');
        }else
        {
            $paramArray=$this->_request->getParams();
            $filters = array(
                '*'   => 'StringTrim'
            );
            $validators = array(
            );
            $input = new Zend_Filter_Input($filters, $validators, $paramArray);
            $addressid=$input->addressid;
            $address=new CAddress();
            if($addressid==0)
            {
                $address=new CAddress();
                $addressid=$address->createAddress(array('uid'=>$_COOKIE[COOKIE_PRE.'uid'],'content'=>$input->address,'add_time'=>time()));
            }
            $addressArray=$address->getDetail($addressid);
            $contact=new COrderContact();
            $data=array(
                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
                'email'=>$_COOKIE[COOKIE_PRE.'username'],
                'company_name'=>$input->company_name,
                'contact_name'=>$input->contact_name,
                'address'=>$addressArray[0]['content'],
                'location_id'=>$input->location_id,
                'code'=>$input->code,
                'city'=>$input->city,
                'phone_number'=>$input->phone_number,
                'fax_number'=>$input->fax_number
            );
            if($data['city']==''||$data['contact_name']==''||$data['code']==''||$data['phone_number']==''||$data['location_id']=='0')
            {
                $this->_redirect(MY_URL.'/product-addcontact');
            }else
            {
/*
                $contactArray=$contact->getAllContacts(0,1,$_COOKIE[COOKIE_PRE.'uid']);

                if($contactArray[0]['contactid']!='')
                {

                    $contact->editContact($contactArray[0]['contactid'],$data);
                    $urlcontactid=$contactArray[0]['contactid'];

                }else
                {

                   $urlcontactid = $contact->createContact($data);

                }
*/
                $urlcontactid = $contact->createContact($data);
                //
                $array=$this->getHelper('Item')->getOrderItemArray();
            	$itemArray=$array['itemArray'];
            	$totalPrice=$array['totalPrice'];
	            foreach ($itemArray as &$value)
	            {
	                unset($value['content']);
	                unset($value['pattern_intro']);
	            }
	            $order=new COrder();
	            $data=array(
	                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
	                'add_time'=>time(),
	                'seller_uid'=>1,
	                'money'=>$totalPrice,
	                'order_string'=>serialize($itemArray),
	                'delivery_days'=>0,
	                'lagnappe'=>0,
	                'LagnappeMesg'=>'',
	                'yunfeiid'=> 0,
	                'yunfeiprice'=> 0,
	                'contactid'=> $urlcontactid,
	                'ieinfo'=> $_SERVER[HTTP_USER_AGENT],
	                'flid'=>1
	            );
	            
	            $order->createOrder($data);
	
	            setcookie(COOKIE_PRE.'product_buy_session',null,-1,'/');
	
	            $this->_redirect(MY_URL.'/product-pay');
				//
                //$this->_redirect(MY_URL.'/product-shipping?location_id='.$input->location_id.'&contactid='.$urlcontactid);
            }
        }
        return true;
    }

    public function shippingAction()
    {

        $member=new CMember();

        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {

            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipping');

        }else
        {

            $contactid=$this->_request->getParam('contactid');
            $location_id=$this->_request->getParam('location_id');

            $CFenlei=new CFenlei("location");

            $onelocationArray=$CFenlei->getoneFenlei($location_id);

            // $pattern_size=unserialize($onelocationArray[0]['product_pattern']);

            // $this->view->assign('pattern_size',is_array($pattern_size)?$pattern_size:array());

            $Cyunfei=new Cyunfei();

            $yunfeiArray=$Cyunfei->getyunfeiIN($onelocationArray[0]['yunfei']);
			print_r($yunfeiArray);
            $this->getHelper('Item')->getLagnappeArray();

            $orderContact=new COrderContact();

            $locationArray=$orderContact->getContactLoaction("uid='".$_COOKIE[COOKIE_PRE.'uid']."'");

            $this->view->assign('locationArray',$locationArray);

            $this->view->assign('yunfeiArray',$yunfeiArray);

            $this->view->assign('contactid',$contactid);

            $this->getHelper('Item')->getOrderItemArray();
        }
    }

    public function doshippingAction()
    {

        if(!$this->_request->isPost())
        {

            $this->_redirect(MY_URL);

            return false;

        }

        $member=new CMember();

        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {

            $this->_redirect(MY_URL.'/auth-login?preurl=product-shipping');

        }else
        {
            $lpid=$this->_request->getParam('lpid');

            $contactid=$this->_request->getParam('contactid');

            $lpsize=$this->_request->getParam('lpsize');

            $yunfeiid=$this->_request->getParam('yunfeiid');

            $LagnappeMesg=$this->_request->getParam('LagnappeMesg');

            $BadgePatch=$this->_request->getParam('BadgePatch');
            
            $select_badgepatch=$this->_request->getParam('select_badgepatch');
            
            $addNameNum=$this->_request->getParam('addNameNum');

            $shirtName=$this->_request->getParam('shirtName');

            $shirtNum=$this->_request->getParam('shirtNum');

            if($lpsize)
            {
                $LagnappeMesgtmp.="Size:".$lpsize."<br>";
            }

            if($BadgePatch)
            {
                $LagnappeMesgtmp.="BadgePatch:".$BadgePatch."<br>";
            }
            if($addNameNum==1)
            {
                $LagnappeMesgtmp.="Print name and number: Name:".$shirtName." Number:".$shirtNum."<br>";
            }else
            {
                $LagnappeMesgtmp.="Print name and number:NO<br>";
            }
            $LagnappeMesg=$LagnappeMesgtmp.$LagnappeMesg;
            $CLagnappe=new CLagnappe();

            $LagnappeArray=$CLagnappe->getDetail($lpid);

            $Cyunfei=new Cyunfei();
            if($yunfeiid)
            {
                $oneyunfeiArray=$Cyunfei->getDetail($yunfeiid);
            }
            $this->_helper->viewRenderer->setNoRender();

            $this->getHelper ('layout')->disableLayout ();

            $array=$this->getHelper('Item')->getOrderItemArray();

            $itemArray=$array['itemArray'];

            $totalPrice=$array['totalPrice'];

            if($LagnappeArray[0]["price"])
            {
                $totalPrice+=$LagnappeArray[0]["price"];
            }

            foreach ($itemArray as &$value)
            {

                unset($value['content']);

                unset($value['pattern_intro']);

            }

            //$totalPrice=$array['totalPrice'];
            if($oneyunfeiArray[0]["price"])
            {
                $totalPrice=$totalPrice+ $oneyunfeiArray[0]["price"];

            }
            if($lpid)
            {
                if($BadgePatch=="Yes")
                {
                    $totalPrice=$totalPrice+ 2;
                }
                if($addNameNum==1)
                {
                    $totalPrice=$totalPrice+ 2;;
                }
            }
            if($oneyunfeiArray)
            {
                $yunfeiprice=$oneyunfeiArray[0]["price"];
            }else
            {
                $yunfeiprice=0;
                $yunfeiid=0;
            }
            $order=new COrder();
            $data=array(
                'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
                'add_time'=>time(),
                'seller_uid'=>1,
                'money'=>$totalPrice,
                'order_string'=>serialize($itemArray),
                'delivery_days'=>0,
                'lagnappe'=>$lpid,
                'LagnappeMesg'=>$LagnappeMesg,
                'yunfeiid'=> $yunfeiid,
                'yunfeiprice'=> $yunfeiprice,
                'contactid'=> $contactid,
                'ieinfo'=> $_SERVER[HTTP_USER_AGENT],
                'flid'=>1
            );

            $order->createOrder($data);

            setcookie(COOKIE_PRE.'product_buy_list',null,-1,'/');

            $this->_redirect(MY_URL.'/product-pay');

        }

        return true;
    }

    public function payAction()
    {
		$this->view->styleName = 'order';
		$this->view->webSiteTitle = 'Pay My Order';
    	$this->view->webSiteKeywords = 'Pay My Order';
    	$this->view->webSiteDescription = 'Pay My Order';
    	
        $member=new CMember();
        if( !$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
            $this->_redirect(MY_URL.'/auth-login?preurl=product-pay');
        } else {
            $order = new COrder();            
            $orderArray = $order->getAllOrders(0,0,$_COOKIE[COOKIE_PRE.'uid'],"has_shutted='0' AND ".R_PRE."orders.flid='1'");
            
            $total = 0;
            foreach ($orderArray as $value) {
                $total += $value['money'];
            }
            $this->view->assign('total',$total);           
            $this->view->assign('orderArray',$orderArray);
            $memberArray = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE.'uid']));
            $this->view->assign('memberArray',$memberArray);
        }

    }

    public function cancelorderAction()
    {
        $this->_helper->viewRenderer->setNoRender();
        $orderid=$this->_request->getParam('orderid');
        $member=new CMember();
        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer')
        {

            $this->_redirect(MY_URL.'/auth-login?preurl=product-pay');

        }else
        {

            $order=new COrder();

            $orderArray=$order->getDetail($orderid);

            if($orderArray[0]['uid']==$_COOKIE[COOKIE_PRE.'uid'])
            {

                $order->editOrder($orderid,array('flid'=>7));

                $this->view->showMsg("Succeed to cancel #PO$orderid!",'product-pay');

            }

        }

    }



    public function moredealsAction()
    {
    	$this->view->webSiteTitle ='Wholesale Soccer Jerseys';
    }
    
   
}
